package statadminlogic

import (
	"context"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"
	"time"

	"navi-mumbai/app/rpc/stat/internal/svc"
	"navi-mumbai/app/rpc/stat/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryLtvStatLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryLtvStatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryLtvStatLogic {
	return &QueryLtvStatLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询LTV统计
func (l *QueryLtvStatLogic) QueryLtvStat(in *pb.QueryLtvStatReq) (*pb.QueryLtvStatResp, error) {
	defer utils.RecoverPanic()

	var start, end int64
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		start, _ = strconv.ParseInt(t.Format(dbkey.DateFormat2), 10, 64)
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		end, _ = strconv.ParseInt(t.Format(dbkey.DateFormat2), 10, 64)
	}
	ltvs, err := l.svcCtx.LifeTimeValueModel.Find(l.ctx, start, end, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var resp pb.QueryLtvStatResp
	resp.List = make([]*pb.LtvData, 0)

	if len(ltvs) <= 0 {
		return &resp, nil
	}

	for i := 0; i < len(ltvs); i++ {
		var vl pb.LtvData
		_ = copier.Copy(&vl, ltvs[i])

		vl.CreateTime = ltvs[i].CreateTime.Format(dbkey.DateTimeCNFormat)

		resp.List = append(resp.List, &vl)
	}

	return &resp, nil
}
